// 引入koa-router
const Router = require('koa2-router');
const router = new Router();
const sql = require('../../config/config');
// 引入model的sql语句
const {
    getNav,
    getGoods1,
    getGoods2,
    getBanner,
    getCarousel,
    getNickname,
    getProducts,
    getProduct,
    getRecommend,
    getCartData,
    getOrderData
} = require("../../model/api/data");
const { getCollect } = require("../../model/api/collect");

// 引入jsonwebtoken模块
const jwt = require("jsonwebtoken");
const SECRET = "hello";

// 主页数据
router.get('/index',async (ctx)=>{
    const token = ctx.request.headers['authorization'];

    let nav  = await getNav();
    let goodsItem1 = await getGoods1();
    let goodsItem2 = await getGoods2();
    let banner = await getBanner();
    let carousel = await getCarousel();

    let nickName = '';
    if (token) {
        // 解密token获取用户id
        let decoded = jwt.verify(token, SECRET);
        // 获取登录用户的昵称
        nickName = await getNickname([decoded.ID]);
        nickName = nickName[0]
        // console.log(nickName);
    }
    // console.log(nav);
    ctx.body = {
        nav,
        goodsItem1,
        goodsItem2,
        banner,
        carousel,
        nickName
    };
});
// 分类数据
router.get('/classify',async (ctx)=>{
    ctx.body = await getProducts();
})
// 详情数据
router.post('/product',async (ctx)=>{
    // 获取token
    const token = ctx.request.headers['authorization'];
    // console.log(ctx.request.headers['authorization']);

    let id = ctx.request.body.id;
    // console.log(id);
    let product = await getProduct([id]);
    // console.log(product);

    if (token){
        // 解密token获取用户id
        let decoded = jwt.verify(token, SECRET);
        // console.log(decoded.ID);
        // 获取登录用户是否在该商品详情页的收藏记录
        let state = await getCollect([decoded.ID,id]);
        // console.log(state[0]);
        ctx.body = [product[0],state[0]];
    }else {
        ctx.body = [product[0]];
    }


})
// 推荐数据
router.get('/recommend',async (ctx)=>{
    let arr = [];
    for (let i=0;arr.length<5;i++){
        let rdm = Math.floor(Math.random()*62+1);
        if (arr.indexOf(rdm)===-1){
            arr.push(rdm);
        }
    }
    // console.log(arr);
    ctx.body = await getRecommend(arr);
})
// 购物车数据
router.get('/cart',async (ctx)=>{
    const token = ctx.request.headers['authorization'];
    // 解密token获取用户id
    let decoded = jwt.verify(token, SECRET);
    // let cart = await sql('select * from cart where userid = ?',[decoded.ID]);
    ctx.body = await getCartData([decoded.ID]);
})
// 订单数据
router.get('/order',async (ctx)=>{
    // console.log(ctx.request.query.order_id);
    let order_id = ctx.request.query.order_id;
    let orderData = await getOrderData([order_id]);
    // console.log(orderData);
    ctx.body = orderData[0];
})

module.exports = router;